package dao;

import model.Course;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author tongchen
 * @create 2022-12-29 11:22
 */
public class CourseDao {
    //创建变量
    Connection connection=null;
    PreparedStatement statement=null;
    ResultSet resultSet=null;
    public List<Course> selectAll(){
        //建立连接
        try {
            connection=DBUtils.getConnection();
            //定义sql
            String sql="select id ,name from course ";
            //创造执行器
            statement=connection.prepareStatement(sql);
            //执行
            resultSet = statement.executeQuery();
            ArrayList<Course> courses=null;
            while(resultSet.next()){
                if(courses==null) {
                    courses = new ArrayList<>();
                }
                    Course course = new Course();
                    course.setId(resultSet.getInt(1));
                    course.setName(resultSet.getString(2));
                    courses.add(course);

            }
            return courses;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //释放资源
            DBUtils.closeResources(connection,statement,resultSet);
        }
    }

}
